//
//  TVStatementViewController.swift
//  StarTimesON
//
//  Created by Toj on 11/15/22.
//  Copyright © 2022 StarTimes. All rights reserved.
//

import UIKit

class TVStatementViewController: STBaseViewController {
    
    private let viewModel = TVStatementViewModel()
    
    private var statements: [TVStatementCellModel] = [] { didSet {
        tableView.isHidden = statements.count == 0
        notDataView.isHidden = !tableView.isHidden
        guard statements.count > 0 else {
            return
        }
        
        tableView.reloadData()
    } }
    
    // 月份
    private lazy var collectionView: UICollectionView = {
        let showCount: CGFloat = 5
        let margin: CGFloat = 8.ui_scale
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = margin
        layout.minimumInteritemSpacing = 0
        let width = (CGFloat.sr_width - margin * showCount) / showCount
        layout.itemSize = CGSize(width: width, height: 32.ui_mnscale)
        
        let view = UICollectionView(frame: .zero, collectionViewLayout: layout)
        view.bounces = false
        view.scrollsToTop = false
        view.alwaysBounceVertical = true
        view.showsVerticalScrollIndicator = false
        view.showsHorizontalScrollIndicator = false
        view.backgroundColor = .white
        view.contentInset = UIEdgeInsets(top: 0, left: margin, bottom: 0, right: margin)
        view.register(TVStatementMonthsCell.cell_class, forCellWithReuseIdentifier: TVStatementMonthsCell.cell_identifier)
        view.dataSource = self
        view.delegate = self
        return view
    }()
    
    private lazy var headerView: TVStatementHeaderView = {
        let view = TVStatementHeaderView()
        view.backgroundColor = "#333333".to_color
        view.headerViewModel = TVStatementHeaderViewModel()
        return view
    }()
    
    private(set) lazy var notDataView: UIImageView = {
        let view = UIImageView()
        view.backgroundColor = .white
        view.contentMode = .center
        view.image = "common".to_image
        view.isHidden = true
        return view
    }()
    
    private lazy var tableView: UITableView = {
        let view = UITableView()
        view.contentInsetAdjustmentBehavior = .never
        
        view.separatorStyle = .none
        view.backgroundColor = UIColor.white
        view.showsVerticalScrollIndicator = false
        view.showsHorizontalScrollIndicator = false
        view.rowHeight = 180.ui_mnscale
        
        view.register(TVStatementCell.cell_class, forCellReuseIdentifier: TVStatementCell.cell_identifier)
        
        view.dataSource = self
        view.delegate = self
        return view
    }()
    
    @objc private func didTapBack() {
        navigationController?.popViewController(animated: true)
    }
    private lazy var leftItem: UIBarButtonItem = {
        let item = UIBarButtonItem(target: self, action: #selector(didTapBack), for: .touchUpInside, imageNormal: "com_nav_back_black")
        return item
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let model = TVStatementCellModel(statement: TVStatementModel())
        statements = [model]
        
        setupMakeAddSubviews()
        setupMakeLayoutSubviews()
        setupMakeInitialize()
    }
    
    var tableViewCellAddresses: [String] = []
    
    var collectionCellAddresses: [String] = []
}

let random = Int(arc4random_uniform(30) + 10)
extension TVStatementViewController: UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print("-->toj: \(random)")
        return random // statements.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
//        var cell = tableView.dequeueReusableCell(withIdentifier: TVStatementCell.cell_identifier, for: indexPath) as? TVStatementCell
//        if cell == nil {
//            cell = TVStatementCell(style: .default, reuseIdentifier: TVStatementCell.cell_identifier)
//        }
        let cell = tableView.dequeueReusableCell(withReuseIdentifierClass: TVStatementCell.self)
        let address = cell.cm_objectAddress
        if !tableViewCellAddresses.contains(address) {
            tableViewCellAddresses.append(address)
        }
        print("-->toj: t cell: \(address)")
        
        cell.statement = statements[0] //statements[indexPath.row]
       
        return cell
    }
}

extension TVStatementViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForItem(at: indexPath, convertTo: TVStatementCell.self)
        print("-->toj: didSelectRowAt cell: \(cell!.cm_objectAddress)")
        
        tableViewCellAddresses.forEach { address in
            print("-->toj: didSelectRowAt address:\(address)")
        }
    }
}

extension TVStatementViewController: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel.months.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        // let cell = collectionView.dequeueReusableCell(withReuseIdentifier: TVStatementMonthsCell.cell_identifier, for: indexPath, convertTo: TVStatementMonthsCell.self)
        let cell = collectionView.dequeueReusableCell(withReuseIdentifierClass: TVStatementMonthsCell.self, for: indexPath)
        let address = cell.cm_objectAddress
        if !collectionCellAddresses.contains(address) {
            collectionCellAddresses.append(address)
        }
        print("-->toj: c cell: \(address)")
        cell.cellModel = viewModel.months[indexPath.row]
        return cell
    }
}

extension TVStatementViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath, convertTo: TVStatementMonthsCell.self)
        print("-->toj: didSelectItemAt cell: \(cell!.cm_objectAddress)")
        
        collectionCellAddresses.forEach { address in
            print("-->toj: didSelectItemAt address:\(address)")
        }
    }
}

// MARK: - 初始化
extension TVStatementViewController {
      
    private func setupMakeAddSubviews() {
        view.addSubview(collectionView)
        view.addSubview(tableView)
        view.addSubview(headerView)
        view.addSubview(notDataView)
    }
    
    private func setupMakeLayoutSubviews() {
        
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(navigationBar.snp.bottom).offset(4.ui_scale)
            make.left.right.equalTo(view)
            make.height.equalTo(32.ui_mnscale)
        }
        
        headerView.snp.makeConstraints { make in
            make.top.equalTo(collectionView.snp.bottom).offset(4.ui_scale)
            make.left.right.equalTo(view).inset(8.ui_scale)
            make.height.equalTo(80.ui_scale)
        }
        
        tableView.snp.makeConstraints { make in
            make.top.equalTo(headerView.snp.bottom).offset(4.ui_scale)
            make.left.right.equalTo(view).inset(12.ui_scale)
            make.bottom.equalTo(view)
        }
        
        notDataView.snp.makeConstraints { make in
            make.edges.equalTo(tableView)
        }
    }
    
    private func setupMakeInitialize() {
        view.backgroundColor = UIColor.white
       
        view.layoutIfNeeded()
        
        headerView.st_corner(cradius: 8, shadow: UIColor.black.tt_alpha(0.4), sopacity: 1, sradius: 5, soffset: CGSize(width: 0, height: 3))
        
        navigationItem.leftBarButtonItem = leftItem
    }
}
